import { createI18n } from "vue-i18n";
import translate from "i18n-jsautotranslate";

// 引入翻译文件
import en from "./locales/en.ts";
import zh from "./locales/zh.ts";
import ja from "./locales/ja.ts";

// 引入element-plus翻译文件
import elEn from "element-plus/es/locale/lang/en";
import elzhCN from "element-plus/es/locale/lang/zh-cn";
import eljA from "element-plus/es/locale/lang/ja";

const messages = {
  en,
  zh,
  ja,
};

// 导出语言选项（用于下拉菜单）
export const LANGUAGE_OPTIONS = [
  { label: "中文", value: "zh" },
  { label: "English", value: "en" },
  { label: "日语", value: "ja" },
];

// 默认语言
export const DEFAULT_LANGUAGE = "zh";

// 获取缓存中的当前语言
const current_lang = localStorage.getItem("SAVED_LANGUAGE_KEY");
// 缓存中无语言就设置缓存默认语言
if (!current_lang) {
  localStorage.setItem("SAVED_LANGUAGE_KEY", DEFAULT_LANGUAGE);
}

export const SAVED_LANGUAGE =
  localStorage.getItem("SAVED_LANGUAGE_KEY") ||
  navigator.language.split("-")[0] ||
  DEFAULT_LANGUAGE;

let elementLangage = elzhCN;
// 处理特定Element组件国际化
export const handleElementLang = () => {
  let lang = SAVED_LANGUAGE;
  switch (lang) {
    case "en":
      elementLangage = elEn;
      break;
    case "zh-cn":
      elementLangage = elzhCN;
      break;
    case "ja":
      elementLangage = eljA;
      break;
  }
  return elementLangage;
};

// 创建i18n实例
export const i18n = createI18n({
  locale: SAVED_LANGUAGE, // 设置默认语言
  fallbackLocale: DEFAULT_LANGUAGE, // 设置备选语言，当前语言的翻译缺失时使用此语言
  messages, // 设置资源
});
